package com.zhoug.demo.player.http;

import com.zhoug.common.content.Optional;
import com.zhoug.common.framework.rxjava2.SchedulerUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import io.reactivex.disposables.Disposable;

/**
 * @author: zhoug
 * @since: 2025-06-20
 */
public class ApiRepository {
    private static final String TAG = ">>>ApiRepository";
    private static List<Disposable> mCache = new ArrayList<>();


    public ApiRepository() {
    }

    public Disposable login(String name, String pwd, String imageCode, String validSerialNumber, boolean UseCode, @NonNull DataCallback<LoginAccount> callback) {

        LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .put(RequestParamsBuild.PARAMS.LoginName, name)
                .put(RequestParamsBuild.PARAMS.Password, pwd)
                .put(RequestParamsBuild.PARAMS.ValidCode, imageCode)
                .put(RequestParamsBuild.PARAMS.ValidSerialNumber, validSerialNumber)
                .put(RequestParamsBuild.PARAMS.LoginMode, UseCode)
                .build();
        Disposable disposable = HttpClient.getInstance().getBaseRequests().login(params)
                .subscribeOn(SchedulerUtils.io())
                .compose(ResponseTransformer.handleResult())
                .observeOn(SchedulerUtils.io())
                .map(loginResponseOptional -> {
                    LoginAccount loginAccount = loginResponseOptional.get();

                    return loginResponseOptional;
                })
                .observeOn(SchedulerUtils.ui())
                .subscribe(s -> callback.onSuccess(s.get()), throwable -> callback.onFailure(throwable.getMessage()));
        return disposable;
    }


    public Disposable getFirmMonitorPlayUrlById(String monitorId, int Protocol, DataCallback<String> callback) {
        LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .withId(monitorId)
                .put("Protocol", Protocol)
//                .put("Clarity", clarity > 0 ? clarity : null)
                .build();
        Disposable disposable = HttpClient.handler(HttpClient.getInstance().getBaseRequests().getFirmMonitorPlayUrlById(params))
                .observeOn(SchedulerUtils.io())
                .map(s -> {
                    FirmMonitor firmMonitor = s.get();
                    if (firmMonitor != null && firmMonitor.getPlayUrl() != null) {
                        String playUrl = firmMonitor.getPlayUrl();
                        if (MyPlayUrlUtil.isPlayUrl(playUrl)) {
                            return Optional.create(playUrl);
                        } else if (StringUtils.isNullOrEmpty(playUrl)) {
                            throw new Exception("播放地址为空");
                        } else {
                            throw new Exception("播放地址格式不正确:" + playUrl);
                        }
                    } else {
                        String error = firmMonitor == null ? "firmMonitor is null" : "PlayUrl is null";
                        LogUtils.e(TAG, "获取摄像头地址失败:" + error);
                        throw new Exception(error);
                    }


                })
                .observeOn(SchedulerUtils.ui())
                .subscribe(s -> {
                    if (callback != null) {
                        callback.onSuccess(s.get());
                    }
                }, throwable -> {
                    if (callback != null) {
                        callback.onFailure(throwable.getMessage());
                    }
                });
        return disposable;

    }

    public void setLifecycleOwner(LifecycleOwner owner){
        if(owner!=null){
            owner.getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    disposable();
                }
            });
        }
    }

    private void addDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            mCache.add(disposable);
        }
    }


    public void disposable() {
        for (Disposable item : mCache) {
            if(item!=null && !item.isDisposed()){
                item.dispose();
            }
        }
        mCache.clear();
    }

}
